package com.link.play.fit.ai.ui.guide

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.link.play.fit.ai.R
import com.link.play.fit.ai.databinding.FgSettingEveryBinding
import com.link.play.fit.ai.ui.guide.ac.GuidePbAc
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlin.random.Random

class SettingEveryFg : BasePageFragment<FgSettingEveryBinding>(FgSettingEveryBinding::inflate) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        val activity = (requireActivity() as GuidePbAc)
        val data = activity.viewModel.userGuideState

        lifecycleScope.launch(Dispatchers.Main) {

            data.collectLatest {
                Log.e(TAG, "$it")

                if (!isVisible) {
//                    Log.e(TAG, "!isVisible")
                    return@collectLatest
                }
                if (activity.currentIndex != pageIndex) {
//                    Log.e(TAG, "activity.currentIndex!=pageIndex")
                    return@collectLatest
                }
//                Log.e(TAG, "SettingEveryFg")

//                if (!it.dataReady) {
//                    Log.e(TAG, "dataReady=false")
                binding.tvLoad.text = getString(R.string.estimating_your_metabolic_age)
                async(Dispatchers.IO) {
                    activity.viewModel.getUserAage()
                    delay(Random.nextLong(1000, 1500))
                }.await()

                binding.tvLoad.text = getString(R.string.applying_bmr_formula)
                async(Dispatchers.IO) {//计算BMR
//                delay(Random.nextLong(1000, 1500))
                    activity.viewModel.getBMR()
                }.await()

                binding.tvLoad.text = getString(R.string.customizing_health_plan)
                async(Dispatchers.IO) {
                    activity.viewModel.customDailyPlan()
                    delay(Random.nextLong(1000, 2500))
                }.await()

                binding.tvLoad.text = getString(R.string.finalizing_results)
                async(Dispatchers.IO) {
                    delay(Random.nextLong(1000, 1500))
                }.await()

                (requireActivity() as GuidePbAc).settingPlanFinish()

//                }
            }
        }


    }

    override fun onResume() {
        super.onResume()
        (requireActivity() as GuidePbAc).viewModel.userGuideState.update {
            it.copy(id = it.id++)
        }

    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        Log.e(TAG, "onResumeOneShoot")
    }


}